import { defineStore } from 'pinia';
import router from '@/router';
import { useAppStore, useTagStore } from '@/store';
import tool from '@/utils/tool';
import authApi from '@/api/auth';

const useAdminStore = defineStore('admin', {
  state: () => ({
    id: undefined,
    name: undefined,
    username: undefined,
    nickname: undefined,
    avatar: undefined,
    full_avatar: undefined,
    email: undefined,
    phone: undefined,
    remark: undefined,
    // adminInfo: {},
    roles: undefined, // 根据角色判断权限
    role_routes: undefined, // 判断路由权限
    routes: undefined,
    count_unreadmsg: 0, // 未读消息
    options: {}, // 配置
  }),
  getters: {
    getState() {
      return { ...this.$state };
    },
  },
  actions: {
    setToken(token) {
      tool.local.set(import.meta.env.VITE_APP_TOKEN_PREFIX, token);
    },
    getToken() {
      return tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX);
    },
    clearToken() {
      tool.local.remove(import.meta.env.VITE_APP_TOKEN_PREFIX);
    },
    setInfo(data) {
      this.$patch(data);
      // this.adminInfo = data;
      // this.adminInfo.avatar = data.full_avatar;
      this.role_routes = data.role_routes;
    },
    resetInfo() {
      this.$reset();
    },

    setMenu(data) {
      const routers = flatAsyncRoutes(filterAsyncRouter(data));
      routers.map(item => router.addRoute('layout', item));
    },
    requestAdminInfo() {
      return new Promise((resolve, reject) => {
        authApi.getProfile().then(async response => {
          if (!response || !response.data) {
            this.clearToken();
            await router.push({name: 'login'});
            reject(false);
          } else {
            this.setInfo(response.data);
            // 获取菜单
            authApi.getMenu().then(async res => {
              this.routers = res.data;
              this.setMenu(this.routers);
              this.routers = removeButtonMenu(this.routers);
              await this.setApp();
              resolve(res.data);
            });
          }
        });
      });
    },

    login(form) {
      return authApi.login(form).then(res => {
        if (res.status === 1) {
          this.setToken(res.data.token);
          return true;
        } else {
          return false;
        }
      }).catch(e => {
        return false;
      });
    },
    async logout() {
      await authApi.logout();
      tool.local.remove('tags');
      const tagStore = useTagStore();
      tagStore.clearTags();
      this.clearToken();
      this.resetInfo();
    },

    async setApp() {
      // const appStore = useAppStore();
      // const setting = this.adminInfo.backend_setting;
      // if (setting) {
      //   appStore.toggleMode(setting?.mode ?? appStore.mode);
      //   appStore.toggleMenu(setting?.menuCollapse ?? appStore.menuCollapse);
      //   appStore.toggleTag(setting?.tag ?? appStore.tag);
      //   appStore.changeMenuWidth(setting?.menuWidth ?? appStore.menuWidth);
      //   appStore.changeLayout(setting?.layout ?? appStore.layout);
      //   appStore.useSkin(setting?.skin ?? appStore.skin);
      //   appStore.changeColor(setting?.color ?? appStore.color);
      // }
    },
  }
});

// 路由扁平化
const flatAsyncRoutes = (routes, breadcrumb=[]) => {
  let newRoutes = [];
  routes.forEach((route, index) => {
    const tmp = {...route};
    if (tmp.children) {
      let childrenBreadcrumb = [...breadcrumb];
      childrenBreadcrumb.push(route);
      let tmpRoute = { ...route };
      tmpRoute.meta.breadcrumb = childrenBreadcrumb;
      delete tmpRoute.children;
      newRoutes.push(tmpRoute);
      let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb);
      childrenRoutes.map(item => {
        newRoutes.push(item);
      });
    } else {
      let tmpBreadcrumb = [...breadcrumb];
      tmpBreadcrumb.push(tmp);
      tmp.meta.breadcrumb = tmpBreadcrumb;
      newRoutes.push(tmp);
    }
  });
  return newRoutes
}

const views = import.meta.glob('../../views/**/**.vue');
const empty = import.meta.glob('../../layout/empty.vue');

// 菜单转换路由
const filterAsyncRouter = (routerMap) => {
  const accessedRouters = [];
  routerMap.forEach(item => {
    const route = {
      path: item.path,
      name: item.name,
      // hidden: item.hidden === 1,
      redirect: item.redirect,
      meta: item.meta,
      children: item.children ? filterAsyncRouter(item.children) : null,
      component: views[`../../views/${item.component}.vue`],
    }
    accessedRouters.push(route);
  })
  return accessedRouters;
}

// 去除按钮菜单
const removeButtonMenu = (routers) => {
  let handlerAfterRouters = [];
  routers.forEach(item => {
    if (item.meta.type !== 'B' && ! item.meta.hideInMenu) {
      let route = item;
      if (item.children && item.children.length > 0) {
        route.children = removeButtonMenu(item.children);
      }
      handlerAfterRouters.push(route);
    }
  })
  return handlerAfterRouters;
}

export default useAdminStore;